// 聊天页面主要功能管理类
class ChatManager {
    constructor() {
        // 基础属性初始化
        this.chatContent = document.getElementById('chat-content');
        this.contactList = document.getElementById('contact-list');
        this.chatTitle = document.getElementById('chat-title');
        this.userId = null;
        this.userName = null;
        this.currentContactId = null;
        this.chatHistories = new Map();
        this.unreadMessages = new Set();  // 添加未读消息集合

        // 立即初始化DOM元素和事件绑定
        this.initializeElements();
        this.bindEvents();

        this.initializeUserAndContacts();

        window.electronAPI.onUpdateContactList((messages) => {
            this.updateContactList(messages);
        });
        
        this.initializeMessagePolling();

        document.addEventListener('visibilitychange', () => {
            if (document.visibilityState === 'visible') {
                this.updateContactListOnly();
            }
        });

        window.addEventListener('focus', () => {
            this.updateContactListOnly();
        });
    }

    // 修改初始化用户数据和联系人列表方法
    async initializeUserAndContacts() {
        try {
            // 获取用户数据
            const userData = await window.clickBtn.getUserDataObject();
            this.userId = userData.userId;
            this.userName = userData.userName;

            // 请求联系人列表
            await this.fetchContacts();
        } catch (error) {
            this.contactList.innerHTML = '<div class="error-message">初始化失败，请刷新页面重试</div>';
        }
    }

    // 从服务器获取联系人列表
    async fetchContacts() {
        try {
            this.contactList.innerHTML = '<div class="loading-indicator">加载中...</div>';

            const response = await fetch(`http://${_HOST_}:${_PORT_}/GetInfo`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    userId: this.userId
                })
            });

            const data = await response.json();

            if (data.code === '0000') {
                this.updateContactList(data.messages);
            } else {
                throw new Error(data.msg || '获取联系人列表失败');
            }
        } catch (error) {
            this.contactList.innerHTML = '<div class="error-message">获取联系人列表失败，请刷新页面重试</div>';
        }
    }

    // 更新联系人列表的方法
    async updateContactListOnly() {
        try {
            const response = await fetch(`http://${_HOST_}:${_PORT_}/Get`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    userId: this.userId,
                    boxType: "contact"
                })
            });

            const data = await response.json();
            if (data.code === '0000' && data.messages) {
                // 只更新联系人列表，不清空聊天记录
                this.updateContactList(data.messages);
            }
        } catch (error) {
            console.error('更新联系人列表失败:', error);
        }
    }

    // 更新联系人列表方法
    updateContactList(messages) {
        // 保存当前选中的联系人ID
        const currentActiveId = this.currentContactId;
        
        // 清空现有联系人列表
        this.contactList.innerHTML = '';

        if (messages && messages.length > 0) {
            const listContainer = document.createElement('div');
            listContainer.className = 'contact-list';

            messages.forEach(item => {
                const contactItem = document.createElement('div');
                contactItem.className = 'contact-item';
                if (item.id === currentActiveId) {
                    contactItem.classList.add('active');
                }
                
                contactItem.innerHTML = `
                    <div class="contact-info">
                        <span class="contact-type">${item.type === 'user' ? '👨' : '👨‍👨‍👦'}</span>
                        <span class="contact-name">${item.name}</span>
                    </div>
                `;

                // 添加点击事件
                contactItem.addEventListener('click', () => {
                    // 移除其他项的选中状态
                    document.querySelectorAll('.contact-item').forEach(elem => {
                        elem.classList.remove('active');
                    });
                    // 添加当前项的选中状态
                    contactItem.classList.add('active');
                    
                    // 只有在切换不同联系人时才清空聊天内容
                    if (this.currentContactId !== item.id) {
                        this.currentContactId = item.id;
                        this.chatTitle.textContent = item.name;
                        this.chatContent.innerHTML = '';
                        
                        // 如果有历史记录，显示历史记录
                        if (this.chatHistories.has(item.id)) {
                            const history = this.chatHistories.get(item.id);
                            history.forEach(msg => {
                                this.appendMessage(msg, msg.isMe);
                            });
                        }
                    }
                });

                listContainer.appendChild(contactItem);
            });

            this.contactList.appendChild(listContainer);
            
            // 如果没有选中的联系人，默认选中第一个
            if (!currentActiveId && listContainer.firstChild) {
                listContainer.firstChild.click();
            }
        } else {
            this.contactList.innerHTML = '<div class="empty-list">您目前好友列表为空~</div>';
        }
    }

    // 添加消息轮询初始化方法
    async initializeMessagePolling() {
        // 确保获取到用户ID
        if (!this.userId || !this.userName) {
            const userData = await window.clickBtn.getUserDataObject();
            this.userId = userData.userId;
            this.userName = userData.userName;
        }
    
        // 开始轮询
        setInterval(async () => {
            try {
                const response = await fetch(`http://${_HOST_}:${_PORT_}/Get`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        userId: this.userId,
                        boxType: "user"
                    })
                });
    
                const data = await response.json();
                
                if (data.code === '0000' && data.messages) {
                    // 过滤出chat类型的消息
                    const chatMessages = data.messages.filter(msg => 
                        msg.message.messageType === 'chat'
                    );
    
                    // 直接使用统一的消息处理方法
                    this.processMessages(chatMessages);
                }
            } catch (error) {
                console.error('获取消息失败:', error);
            }
        }, 1000);
    }

    // 修改发送消息方法
    async sendMessage(message) {
        try {
            // 获取用户数据
            if (!this.userId || !this.userName) {
                const userData = await window.clickBtn.getUserDataObject();
                this.userId = userData.userId;
                this.userName = userData.userName;
            }
            
            if (!this.currentContactId || !this.userId) {
                alert('发送失败：请先选择联系人');
                return false;
            }
            
            // 获取当前联系人类型（用户/群组）
            const contactTypeElement = document.querySelector('.contact-item.active .contact-type');
            const isGroup = contactTypeElement.textContent === '👨‍👨‍👦';
            
            // 构建发送数据
            const sendData = {
                userId: this.userId,
                userName: this.userName,
                groupName: isGroup ? this.chatTitle.textContent : "", // 如果是聊，使用当前聊天标题作为群名
                receiverId: this.currentContactId,
                messageType: "chat",
                context: message.content,
                boxType: isGroup ? "group" : "user"
            };

            const response = await fetch(`http://${_HOST_}:${_PORT_}/Send`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(sendData)
            });

            const result = await response.json();
            
            if (result.code === '0000') {
                // 发送成功，添加到本地聊天记录
                if (!this.chatHistories.has(this.currentContactId)) {
                    this.chatHistories.set(this.currentContactId, []);
                }
                
                const messageData = {
                    username: this.userName,
                    content: message.content,
                    isMe: true
                };
                
                this.chatHistories.get(this.currentContactId).push(messageData);
                this.appendMessage(messageData, true);
                return true;
            } else {
                throw new Error(result.msg || '服务器返回错误');
            }
        } catch (error) {
            alert('发送消息失败：' + error.message);
            return false;
        }
    }

    // 在 bindEvents 方法中添加发送消息的事件监听
    bindEvents() {
        // 发送按钮点击事件
        this.sendBtn.addEventListener('click', async () => {
            const message = this.messageInput.value.trim();
            if (message && this.currentContactId) {
                this.sendBtn.disabled = true; // 发送时禁用按钮
                try {
                    const success = await this.sendMessage({
                        content: message
                    });
                    if (success) {
                        this.messageInput.value = ''; // 只在发送成功时清空输入框
                    }
                } finally {
                    this.sendBtn.disabled = false; // 无论成功失败都重新启用按钮
                }
            }
        });

        // Enter键发送消息
        this.messageInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.sendBtn.click();
            }
        });
    }

    // 添加创建消息元素的辅助方法
    createMessageElement(message, isMe) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message-wrapper ${isMe ? 'message-right' : 'message-left'}`;

        const messageContent = `
            <div class="message-container">
                <div class="username">${message.username}</div>
                <div class="message-content">
                    <div class="message-bubble">
                        ${message.content}
                    </div>
                </div>
            </div>
        `;

        messageDiv.innerHTML = messageContent;
        return messageDiv;
    }

    // 添加消息到聊天界面的方法
    appendMessage(message, isMe) {
        const messageElement = this.createMessageElement(message, isMe);
        this.chatContent.appendChild(messageElement);
        this.scrollToBottom();
    }

    // 滚动到底部的辅助方法
    scrollToBottom() {
        this.chatContent.scrollTop = this.chatContent.scrollHeight;
    }

    // 添加这个方法
    initializeElements() {

        // 聊天相关元素
        this.messageInput = document.getElementById('message-input');
        this.sendBtn = document.getElementById('send-btn');
    }

    // 修改消息处理方法
    processMessages(messages) {
        messages.forEach(msg => {
            const message = msg.message;
            const messageId = msg._id;
            const senderId = message.boxType === "group" ? message.groupId : message.senderId;
            
            const messageData = {
                _id: messageId,
                username: message.senderName,
                content: message.context,
                isMe: message.senderId === this.userId
            };
            
            if (!this.chatHistories.has(senderId)) {
                this.chatHistories.set(senderId, []);
            }
            
            const messageExists = this.chatHistories.get(senderId).some(
                existingMsg => existingMsg._id === messageId
            );
            
            if (!messageExists) {
                this.chatHistories.get(senderId).push(messageData);
                
                if (this.currentContactId === senderId) {
                    this.appendMessage(messageData, messageData.isMe);
                } else if (!messageData.isMe) {
                    // 如果不是当前联系人且不是自己发送的消息，添加未读标记
                    this.unreadMessages.add(senderId);
                    this.updateUnreadStatus(senderId);
                }
            }
        });
    }

    // 添加更新未读状态的方法
    updateUnreadStatus(senderId) {
        const contactItem = document.querySelector(`.contact-item[data-id="${senderId}"]`);
        if (contactItem) {
            if (this.unreadMessages.has(senderId)) {
                contactItem.classList.add('unread');
            } else {
                contactItem.classList.remove('unread');
            }
        }
    }
}
// 初始化聊天管理器
const chatManager = new ChatManager();

